/**
 * Created by zaranengap on 2017/10/17.
 */
import React from 'react';
import {connect} from 'react-redux';
import {Row, Col, Card, Icon, Modal, Button,Checkbox, message} from 'antd';
import 'styles/dashboard-admin.scss';
import {messages, isEmptyObj} from "share/common";
import {ImageUpload} from 'components/index';
import DAService from 'containers/dashboard-admin.service';
import BaseService from 'share/base.service';
import config from 'config';
import menuRoute from 'routes/menuRoute';
import LogoImg from 'images/logo.png';
import ManageImg from 'images/dashboard-admin/app-management.png'
import CompanyImg from 'images/dashboard-admin/icon-company.png'
import ComputerImg from 'images/dashboard-admin/icon-computer.png'
import DepartImg from 'images/dashboard-admin/icon-department.png'
import EmployeeImg from 'images/dashboard-admin/icon-employee.png'
import PhoneImg from 'images/dashboard-admin/icon-phone.png'
import UserAgreementImg from 'images/dashboard-admin/user-agreement.png'
import moment from 'moment'
class DashboardAdmin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalIsShow: false,
      uploadedImages: [],//已经上传的logo
      showCustomLogo: false,//是否显示自定义的logo
      cards: [
        {
          title: messages('dashboard.key1'/*在职员工数量（人）*/),//'在职员工数量（人）',
          img: EmployeeImg,
          number: 0,
          url: menuRoute.getRouteItem('person-manage') ? menuRoute.getRouteItem('person-manage').url : null
        },
        {
          title: messages('dashboard.key2'/*启用部门数量（个）*/),//'启用中的部门数量（个）',
          img: DepartImg,
          number: 0,
          url: menuRoute.getRouteItem('org-structure') ? menuRoute.getRouteItem('org-structure').url : null
        },
      ],
      customCards: [
        {
          title: messages('dashboard.key175')/*用户协议设置*/,
          content: messages('dashboard.key176')/*员工使用产品时需遵守的公司制度*/,
          img: UserAgreementImg,
          platform: [PhoneImg, ComputerImg],
          url: menuRoute.getRouteItem('user-agreement').url
        }, {
          title: messages('dashboard.key177')/*App应用管理*/,
          content: messages('dashboard.key178')/*App端启用的应用和显示的菜单*/,
          img: ManageImg,
          platform: [PhoneImg],
          url: menuRoute.getRouteItem('sub-application').url
        }
      ],
      userAgreementIsEnabled: false,
      userAgreementUrl: menuRoute.getRouteItem('user-agreement') ? menuRoute.getRouteItem('user-agreement').url : null,
      remainedDay: 0,
    };
  }

  componentWillMount() {
    this.daysRemaining();
  };

  componentDidMount() {
    this.getTenantInfo()
  };

  getTenantInfo = () => {
    DAService.getTenantInfo()
      .then((res) => {
        this.setCards(res.data)
      });
    DAService.getUserAgreementByTenantId()
      .then((res) => {
        let data = res.data;
        this.setState({
          userAgreementIsEnabled: data.enabled,
        })
      })
  };

  setCards = (data) => {
    // {"validCorporation":33,"validUser":130,"validDepartment":203,"validCompany":1}
    let cards = this.state.cards;
    if (!isEmptyObj(data)) {
      for (let key in data) {
        if (key === "validUser") {
          cards[0].number = data[key]
        }
        if (key === "validDepartment") {
          cards[1].number = data[key]
        }
        if (key === "validCompany") {
          //新公司才有
          if (!this.props.isOldCompany) {
            cards[2] = {
              title: messages('dashboard.key3'/*启用公司数量（个）*/),
              img: CompanyImg,
              number: data[key],
              url: menuRoute.getRouteItem('company-maintain') ? menuRoute.getRouteItem('company-maintain').url : null
            }
          }
        }
        if (key === "validCorporation") {
          //老公司才有
          if (this.props.isOldCompany) {
            cards[2] = {
              title: messages('dashboard.key4'/*启用法人实体（人）*/),
              img: CompanyImg,
              number: data[key],
              url: menuRoute.getRouteItem('legal-person') ? menuRoute.getRouteItem('legal-person').url : null
            };
          }
        }
      }
      this.setState(
        cards
      )
    }
  };
  setLogoImages = () => {
    let uploadedImages = [];
    let uploadedImage = this.getUploadedImage(this.props.tenant);
    if (uploadedImage) {
      uploadedImages = [uploadedImage]
    }
    this.setState({
      uploadedImages,
      showCustomLogo: this.props.tenant.showCustomLogo ? this.props.tenant.showCustomLogo : false
    })
  };
  getUploadedImage = (data) => {
    let uploadedImage = null;
    if (data.logoURL) {
      uploadedImage = {};
      uploadedImage.iconURL = data.logoURL;
      uploadedImage.fileURL = data.logoURL;
      uploadedImage.thumbnailUrl = data.logoURL;
      uploadedImage.attachmentOID = "logo";
      uploadedImage.fileName = `logo.${data.logoURL.split('/logo/')[1].split('?')[0].split('.')[1] || 'png'}`;
    }
    return uploadedImage;
  };
  showSetModal = () => {
    this.setState({
      modalIsShow: true,
    },()=>{
      this.setLogoImages()
    })
  };
  hideSetModal = () => {
    this.setState({
      modalIsShow: false,
    })
  };
  setComfirm = () => {
    let uploadedImages = this.state.uploadedImages;
    if (uploadedImages.length === 0) {
      DAService.deleteImgId(this.props.tenant.id)
        .then((res) => {
          // 接口设置了租户特性
          // 重新设置一个 redux 控制全局的一些特性
          BaseService.getTenant(this.props.tenant.id);
        })
    }
    let data = {
      "tenantId": this.props.tenant.id,
      "showCustomLogo": this.state.showCustomLogo,
    };
    DAService.updateTenantInfo(data)
      .then((res) => {
        // 接口设置了租户特性
        // 重新设置一个 redux 控制全局的一些特性
        BaseService.getTenant(this.props.tenant.id);
        this.setState({
          modalIsShow: false,
        })
      })
  };
  //是否用自定义logo
  onImageUseChange = (e) => {
    this.setState({
      showCustomLogo: e.target.checked
    })
  };

  //上传图片后的回调函数
  handleUploadImageChange = (fileList) => {
    fileList.map(item=>{
      item.attachmentOID = item.id;
      item.status = 'done';
      item.fileURL = item.logoURL;
      item.fileName = `logo.${item.logoURL.split('/logo/')[1].split('?')[0].split('.')[1] || 'png'}`;
    });
    this.setState({
      uploadedImages: fileList
    })
  };

  //查看用户协议
  goUserAgreement = () => {
    this.context.router.push(this.state.userAgreementUrl)
  };

  jumpNav = (url) => {
    if (url) {
      this.context.router.push(url)
    } else {
      message.warn(messages('dashboard.key183')/*没有权限访问此菜单*/);
    }
  };
  renderCards = () => {
    return this.state.cards.map((card, index) => (
      <Col span={8} key={index}>
        <Card className="card-list" onClick={() => this.jumpNav(card.url)}>
          <Icon type={card.icon} style={{fontSize: 50, color: card.color}}/>
          <div className="number-block">
            <div className="title">{card.title}</div>
            <div className="number">{card.number}</div>
          </div>
          <img src={card.img}/>
        </Card>
      </Col>
    ))
  };

  validDate = () => {
    const { remainedDay } = this.state;
    let content = messages('dashboard.key186',{arg1:(30 - remainedDay > 0) ? (30 - remainedDay) : 0})/*您的免费试用剩余&nbsp;&nbsp;<span style="color: red">{arg1}</span>&nbsp;&nbsp;天，请联系汇联易*/
    Modal.warning({
      title:  <div style={{paddingLeft: 38, wordBreak: "break-word"}} dangerouslySetInnerHTML={{__html: content}}/>,
      content: '400 829 7878',
    });
  };

  invalidDate = () => {
    Modal.warning({
      title: <div style={{paddingLeft: 38, wordBreak: "break-word"}}>
        {messages('expense-parent-report.key166')/*您的免费试用已经到期，请联系汇联易*/}
      </div>,
      content: '400 829 7878',
      width: 426,
    });
  };

  daysRemaining = () => {
    const { tenant } = this.props;
    let startArr = moment(tenant.createdDate).format('YYYY-MM-DD').split("-");
    let endArr = moment(new Date()).format('YYYY-MM-DD').split("-");
    let startDate = new Date(startArr[0], startArr[1], startArr[2]);
    let endDate = new Date(endArr[0], endArr[1], endArr[2]);
    let days = (endDate - startDate) / (24 * 60 * 60 * 1000);
    this.setState({
      remainedDay: days,
    })
  };

  render() {
    const { tenant } = this.props;
    const { userAgreementIsEnabled, cards, customCards, remainedDay } = this.state;
    return (
      <div className="dashboard-admin background-transparent">
        <div className="helios-page-header">
          <div className="f-left">
            <div className="img-wrap">
              {tenant.logoURL ? <img src={tenant.logoURL}/> : <img src={LogoImg}/>}
            </div>
            <div className="company-content">
              <p className="company-name">{tenant.tenantName}</p>
              <p className="company-detail">
                <span>
                  {`${messages('dashboard.key5'/*创建时间*/)}: ${new Date(tenant.createdDate).format('yyyy-MM-dd')}`}
                </span>
                {
                  !tenant.licensed && tenant.status === "TRAIL" &&
                    <span className="company-probation company-probation-valid"
                          onClick={this.validDate}>
                      {messages('dashboard.key187',{arg1:(30 - remainedDay > 0) ? (30 - remainedDay) : 0})/*剩余试用期{arg1}天*/}&nbsp;
                      <div className='triangle'/>&nbsp;
                    </span>
                }
                {
                  !tenant.licensed && tenant.status === "TRIAL_EXPIRED" &&
                    <span className="company-probation company-probation-invalid"
                          onClick={this.invalidDate}>
                      {messages('dashboard.key188')/*试用期已到期*/}&nbsp;<div className='triangle'/>&nbsp;
                    </span>
                }
              </p>
            </div>
          </div>
          <Button shape="circle" icon="setting" size="large" className="f-right btn-setting" onClick={this.showSetModal}/>
        </div>

        <div className="tenant-setting">
          <h2>{messages('dashboard.key179')/*企业设置*/}</h2>
          <Row className="setting-card" gutter={20}>
            {cards.map((card, index) => (
              <Col span={8} key={index}>
                <Card className="card-list" onClick={() => this.context.router.push(card.url)}>
                  <div className="number-block">
                    <div className="title">{card.title}</div>
                    <div className="number">{card.number}</div>
                  </div>
                  <img src={card.img}/>
                </Card>
              </Col>
            ))}
          </Row>
        </div>
        <div className="tenant-setting">
          <h2>{messages('dashboard.key180')/*自定义设置*/}</h2>
          <p>{messages('dashboard.key181')/*在这里您可以通过设置APP/WEB端的自定义显示，让产品更贴近您的企业形象*/}</p>
          <Row className="setting-card" gutter={20}>
            {customCards.map((card, index) => (
              <Col span={8} key={index}>
                <Card className="card-list custom-card" onClick={() => this.context.router.push(card.url)}>
                  <img src={card.img}/>
                  <div className="card-name">
                    <div className="title">{card.title}</div>
                    <div className="content">{card.content}</div>
                    <div className="platform">
                      <p> {messages('dashboard.key182')/*使用平台*/}：{card.platform.map(img => <img src={img}/>)}
                        {index === 0 && (<span className={userAgreementIsEnabled ? "enabled-tag" : "disabled-tag"}>{userAgreementIsEnabled ? messages("common.enabled") : messages("common.disabled")}</span>)}
                      </p>
                    </div>
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
        </div>

        <Modal
          className="set-dashadmin-tenant-modal-wrap"
          title={messages('dashboard.key7'/*编辑企业信息*/)}
          width={600}
          onCancel={this.hideSetModal}
          visible={this.state.modalIsShow}
          footer={[
            <Button key="back" onClick={this.hideSetModal}>
              {messages('dashboard.key8'/*取消*/)}
            </Button>,
            <Button type="primary"
                    onClick={this.setComfirm}>
              {messages('dashboard.key9'/*确定*/)}
            </Button>,
          ]}
        >
          <div>
            <div className="company-name">
              <div className="company-name-title">
                {messages('dashboard.key10'/*企业名*/)}
              </div>
              <div className="company-name-text">{tenant.tenantName}</div>
            </div>
            <div className="company-logo">
              <div className="company-name-title">
                {messages('dashboard.key11'/*企业LOGO*/)}
              </div>
              <div className="img-wrap">
                <ImageUpload
                  uploadUrl={config.baseUrl + "/api/tenant/upload/logo/" + tenant.id}
                  attachmentType="INVOICE_IMAGES"
                  fileType={["PNG", 'png', 'JEPG', 'jepg', 'jpg', 'JPG', 'bmp', 'BMP', "jpg", "JPG", "jpeg", "JPEG"]}
                  defaultFileList={this.state.uploadedImages}
                  onChange={this.handleUploadImageChange}
                  maxNum={1}/>
              </div>
              <div className="img-tips">
                {messages('dashboard.key12'/*建议上传图片尺寸为390*390，大小不超过2M*/)}
              </div>
              <div>
                <Checkbox checked={this.state.showCustomLogo} onChange={this.onImageUseChange}>
                  {messages('dashboard.key13'/*在APP启动页及PC端显示该logo*/)}
                </Checkbox>
              </div>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

DashboardAdmin.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenant: state.login.tenant,
    isOldCompany: state.login.isOldCompany,

  }
}

export default connect(mapStateToProps)(DashboardAdmin);
